<template>
  <view class="jq_info">
    <u-navbar
      safeAreaInsetTop
      fixed
      leftIconColor="#fff"
      leftText="景区信息"
      :autoBack="true"
      bgColor="transparent"
    />

    <view class="jq_content" v-if="JSON.stringify(infoObj) != '{}'">
      <view class="info">
        <view class="top">
          <image class="" :src="infoObj.jingquPictureUrl" />
        </view>
        <view class="top_card">
          <uni-card class="card">
            <view class="card_info">
              <view class="name">{{ infoObj.jingquName }} </view>
              <view class="tips" v-if="infoObj.jingquTips">
                <text
                  v-for="(i, index) in infoObj.jingquTips"
                  :key="index"
                  :class="index == 0 ? 'one_tips' : 'other_tips'"
                  >{{ i }}</text
                >
              </view>
              <view class="open">
                <text class="title"> 开园时间： </text>
                <text class="time">
                  {{ infoObj.jingquOpenTime }}-{{ infoObj.jingquCloseTime }}
                </text>
              </view>
              <view class="open open2">
                <view class="open2_address">
                  <text class="title"> 景区地址： </text>
                  <text class="title">
                    {{ infoObj.jingquAddress }}
                  </text>
                  <uni-icons style="margin-left: 10rpx;" type="paperplane-filled" size="12"  @click="toNavigation"></uni-icons>
                  <!-- <view class="daohang" @click="toNavigation">
                  <uni-icons type="paperplane-filled" size="12"></uni-icons>
                  <text class=""> 导航 </text>
                </view> -->
                </view>
              </view>
  
              <view class="notice_v" v-if="noticeText">
                <u-notice-bar
                  color="#FF7F00"
                  bgColor="#FFF0E2"
                  :speed="60"
                  :text="noticeText"
                  @click="clickNotice"
                >
                </u-notice-bar>
              </view>
            </view>
          </uni-card>
        </view>
          
        <view class="bottom">
          <view class="tabs">
            <u-tabs :list="list4" @click="clickTabs" :current="isActiveTabs"></u-tabs>
          </view>
          <view class="bottom_info">
            <view class="tabs_1" v-if="isActiveTabs == 0">
              <view v-html="infoObj.jingquText"></view>
            </view>
            <view class="tabs_2" v-if="isActiveTabs == 1">
              <view
                style="
                  width: 710rpx;
                  height: 2rpx;
                  background: #f3f3f3;
                  box-sizing: border-box;
                  margin: 0 auto;
                "
              ></view>

              <!-- 导航 -->
              <info-nav :piaoInfoArr="piaoInfoArr" @click-day="clickDay" />
              <!-- 选票 -->
              <choose-piao-num
                :dayPiao="dayPiao"
                @choose-piao="choosePiao"
                @minus-num="minusNum"
                @plus-num="plusNum"
              />
              <!-- 预定 -->
              <fix-piao
                :byAllPiaoNum="byAllPiaoNum"
                :allPrice="allPrice"
                :isDesc="true"
                btnTitle="预定"
                @to-pay="toPay"
                @ticket-desc="ticketDesc"
              />
            </view>
            <view class="" v-if="isActiveTabs == 2">
              <PingJiaInfo :pingjiaInfo="pingjiaInfo" />
              <view class="pingjia_num">
                <view
                  v-for="(i, index) in pingjiaNum"
                  :key="index"
                  @click="clickPJNum(index)"
                  :class="isChooseInfo == index ? 'isChooseInfo' : ''"
                >
                  <text>{{ i.text }}{{ pingjiaNumArr[index] }}</text>
                </view>
              </view>

              <view>
                <view v-for="(i, index) in pingjiaListArr" :key="index">
                  <PingJiaObj :itemInfo="i" />
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <u-skeleton v-else :loading="true" :animate="true"></u-skeleton>
    <u-modal :show="isShowDesc" @confirm="isShowDesc = false">
      <view class="slot-content">
        <rich-text :nodes="descInfo"></rich-text>
      </view>
    </u-modal>
    <image
      v-if="isActiveTabs == 0"
      class="to_bobao"
      :src="config.imgUrl + 'liveAction/to_boBao.png'"
      @click="toBoBao"
    />
  </view>
</template>

<script>
import { getDetailsByJingquIdAPI } from "@/api/jingqu";
import {
  geTicketResidueApi,
  getDayMenpiaoNumApi,
  createOrderApi,
  getOrderDetailsByIdApi,
  pingjiaInfoApi, // 获取景区的评价好评率等信息
  pingjiaListApi, // 获取评价信息
} from "@/api/jingqu/piao";

import InfoNav from "./common/InfoNav.vue";
import ChoosePiaoNum from "./common/ChoosePiaoNum.vue";
import FixPiao from "./common/FixPiao.vue";
// 评价相关
import PingJiaInfo from "./common/PingJiaInfo.vue"; // 好评率等
import PingJiaObj from "./common/PingJiaObj.vue"; // 评价信息

export default {
  components: {
    InfoNav,
    ChoosePiaoNum,
    FixPiao,
    PingJiaInfo,
    PingJiaObj,
  },
  data() {
    return {
      config: getApp().globalData.config,
      // 评价相关
      total: 0,
      pingjiaInfo: {
        goodPercent: 100,
        goodPingjiaCount: 0,
        orderCount: 0,
        pingjiaCount: 0
      },
      pingjiaNum: [{ text: "全部" }, { text: "好评" }, { text: "有图" }],
      isChooseInfo: 0,
      pingjiaNumArr: [0, 0, 0], // 显示评价数量
      pingjiaListArr: [], // 显示评价列表
      params0: {
        jingquId: 0,
        pageNum: 1,
        pageSize: 10,
        type: 0,
      },
      params1: {
        jingquId: 0,
        pageNum: 1,
        pageSize: 10,
        type: 1,
      },
      params2: {
        jingquId: 0,
        pageNum: 1,
        pageSize: 10,
        type: 2,
      },

      lat: null,
      lon: null,
      dayTime: "", // 保存选择的是哪一天

      isShowDesc: false, // 显示票务说明
      descInfo: "", //票务说明

      allPrice: 0, // 计算总价格
      byAllPiaoNum: 0, // 一共购买了几张票
      latitude: 0,
      longitude: 0,
      menutop: "", //组件距离顶部的距离

      isActiveTabs: 0,
      jingquId: 0,
      noticeText: "需提前一天预定，刷本人身份证入园",
      infoObj: {},
      list4: [
        {
          name: "详情",
        },
        {
          name: "购票",
        },
        {
          name: "评价",
        },
      ],
      piaoInfoArr: [], // 景区对应的门票信息
      dayPiao: [], // 获取某天的门票数量
    };
  },

  onLoad(params) {
    console.log(params);
    // isFlag == true, 就是从首页跳转来的，否则就是从上一个页面跳转来的
    let isFlag = params.isFlag ? true : false;

    this.jingquId = Number(params.jingquId);
    this.params0.jingquId =
      this.params1.jingquId =
      this.params2.jingquId =
        this.jingquId;

    if(isFlag){
      this.clickTabs({index: 1});
    }
    this.getJingQuInfo(this.jingquId); // 通过id获取景区详情
  },

  onShow() {},

  methods: {
    // 跳转到景点播报
    toBoBao() {
      uni.navigateTo({
        url: `/pages/liveAction/viewPlayer/viewPlayer?id=${this.jingquId}`,
      });
    },

    getpingjiaNum() {
      pingjiaListApi({
        jingquId: this.jingquId,
        pageNum: 1,
        pageSize: 10,
        type: 0,
      }).then((res) => (this.pingjiaNumArr[0] = res.total));
      pingjiaListApi({
        jingquId: this.jingquId,
        pageNum: 1,
        pageSize: 10,
        type: 1,
      }).then((res) => (this.pingjiaNumArr[1] = res.total));
      pingjiaListApi({
        jingquId: this.jingquId,
        pageNum: 1,
        pageSize: 10,
        type: 2,
      }).then((res) => (this.pingjiaNumArr[2] = res.total));
    },

    getpingjiaList() {
      let params = {};
      if (this.isChooseInfo == 0) {
        params = this.params0;
      } else if (this.isChooseInfo == 1) {
        params = this.params1;
      } else {
        params = this.params2;
      }
      console.log(
        this.pingjiaListArr.length,
        this.pingjiaNumArr[this.isChooseInfo]
      );

      if (this.isActiveTabs == 2) {
        if (
          this.pingjiaListArr.length &&
          this.pingjiaListArr.length >= this.total
        ) {
          console.log(2222);
          uni.showToast({
            title: "没有更多了",
            icon: "none",
          });
          return;
        }
      }

      pingjiaListApi(params)
        .then((res) => {
          if (res.code == 200) {
            const nextDataList = res.rows;
            this.total = res.total;

            if (nextDataList.length > 0) {
              console.log(this.pingjiaListArr.length, res.total);
              for (let i = 0; i < nextDataList.length; i++) {
                if (
                  nextDataList[i].pingjiaPictureUrl &&
                  typeof nextDataList[i].pingjiaPictureUrl == "string"
                ) {
                  nextDataList[i].pingjiaPictureUrl =
                    nextDataList[i].pingjiaPictureUrl.split(",");
                } else {
                  nextDataList[i].pingjiaPictureUrl = [];
                }
              }

              this.pingjiaListArr = this.pingjiaListArr.concat(nextDataList);

              if (this.isChooseInfo == 0) {
                this.params0.pageNum++;
              } else if (this.isChooseInfo == 1) {
                this.params1.pageNum++;
              } else {
                this.params2.pageNum++;
              }
            }
          } else {
            this.pingjiaListArr = [];
          }
          uni.stopPullDownRefresh();
        })
        .catch((err) => {
          this.pingjiaListArr = [];
          uni.stopPullDownRefresh();
        });
    },

    clickPJNum(index) {
      if (this.isChooseInfo != index) {
        this.isChooseInfo = index;
        this.total = 1;
      }
      this.getNewInfo();
    },

    // 通过景区id获取7天的门票总量及剩余
    getPiaoByJingquIdFun() {
      geTicketResidueApi(this.jingquId)
        .then((res) => {
          if (res.code === 200) {
            this.piaoInfoArr = res.data;

            for (let i = 0; i < this.piaoInfoArr.length; i++) {
              if (this.piaoInfoArr[i].menpiaoNum < 100) {
                this.piaoInfoArr[i].isLack = true;
              } else {
                this.piaoInfoArr[i].isLack = false;
              }
            }
            this.clickDay(this.piaoInfoArr[0]);
          } else {
            this.piaoInfoObj = [];
          }
        })
        .catch((err) => {
          this.piaoInfoObj = [];
        });
    },

    // 查询景区选中日期的门票种类及数量
    clickDay(item) {
      this.dayTime = item.date;
      let params = {
        date: item.date,
        jingquId: this.jingquId,
      };
      getDayMenpiaoNumApi(params)
        .then((res) => {
          if (res.code == 200) {
            this.dayPiao = res.data;
            // 用于计算每个类型的票的数量
            this.dayPiao.forEach((piao) => (piao.piaoNumber = 0));
            // 给每一个时间添加上isActive，用于判断是否选中
            this.dayPiao.forEach((day) => {
              day.timeAndNumVos.forEach((timeAndNum) => {
                timeAndNum.isActive = false;
              });
            });
          } else {
            this.dayPiao = [];
          }
        })
        .catch((err) => {
          this.dayPiao = [];
        });
    },

    // 票务说明
    ticketDesc() {
      this.dayPiao.forEach((item) => {
        this.descInfo += `${item.menpiaoNote}<br>`;
      });
      this.isShowDesc = true;
    },

    // 去支付
    toPay() {
      let piaoArr = [];

      // 1 生成订单参数
      const orderInfo = {
        jingquId: this.jingquId,
        orderDate: this.dayTime, // 订单日期(yyyy-MM-dd)
        orderDetails: [],
      };

      // 2 生成订单参数
      this.dayPiao.forEach((item) => {
        // console.log(item);
        item.timeAndNumVos.forEach((item2) => {
          // console.log(item2);
          if (item2.isActive && item.piaoNumber) {
            orderInfo.orderDetails.push({
              menpiaoNumId: item2.menpiaoNumId,
              orderNum: item.piaoNumber,
              orderPrice: item2.price,
            });
          }
        });
      });

      createOrderApi(orderInfo)
        .then((res) => {
          if (res.code === 200) {
            uni.showToast({
              icon: "success",
              title: "预定成功",
            });
            uni.setStorageSync("orderId", res.data + "");
            getOrderDetailsByIdApi(res.data)
              .then((res) => {
                // console.log(res);
                if (res.code === 200) {
                  const item = JSON.stringify(res.data);
                  uni.navigateTo({
                    url: `./payOrder?item=${item}`,
                  });
                }
              })
              .catch((err) => {
                console.log(err);
              });
          } else {
            uni.showToast({
              icon: "error",
              title: "预定失败",
            });
          }
        })
        .catch((err) => {
          console.log(err);
          uni.showToast({
            icon: "error",
            title: "预定失败",
          });
        });
    },

    // 计算总价格
    calculateTotalPrice() {
      this.allPrice = 0;

      this.dayPiao.forEach((item1) => {
        // console.log(item1, "item1");
        const num = item1.piaoNumber;
        item1.timeAndNumVos.forEach((item2) => {
          // console.log(item2, "item2");
          if (num > 0 && item2.isActive) {
            this.allPrice += num * item2.price;
          }
        });
      });
    },

    // 计算一共买了几张票
    calculateTotal() {
      this.byAllPiaoNum = 0;

      this.dayPiao.forEach((item1) => {
        this.byAllPiaoNum += item1.piaoNumber;
      });
    },

    // 数量减
    minusNum(index) {
      // 一切换，就让他重新选
      // 1 先判断是否选中了时间段
      let isChooseTime = false;
      this.dayPiao.forEach((item) => {
        item.timeAndNumVos.forEach((item2) => {
          if (item2.isActive) {
            isChooseTime = true;
          }
        });
      });

      if (this.dayPiao[index].piaoNumber > 0 && isChooseTime) {
        this.dayPiao[index].piaoNumber--;
        this.calculateTotal();
        this.calculateTotalPrice();
      }
      this.$forceUpdate();
    },

    // 数量加
    plusNum(index) {
      // 1 先判断是否选中了时间段
      let isChooseTime = false;
      this.dayPiao.forEach((item) => {
        item.timeAndNumVos.forEach((item2) => {
          if (item2.isActive) {
            isChooseTime = true;
          }
        });
      });

      // 2 然后判断该时间段的总个数
      const item = this.dayPiao[index];
      let timeAllNum = 0;
      for (let i = 0; i < item.timeAndNumVos.length; i++) {
        if (item.timeAndNumVos[i].isActive) {
          timeAllNum = item.timeAndNumVos[i].restNum;
        }
      }

      // console.log(isChooseTime, timeAllNum, this.dayPiao[index].piaoNumber);

      // 3 这两个条件都满足
      if (isChooseTime && timeAllNum > this.dayPiao[index].piaoNumber) {
        this.dayPiao[index].piaoNumber++;
        this.calculateTotal();
        this.calculateTotalPrice();
      }
      this.$forceUpdate();
    },

    // 选择门票
    choosePiao(index2, index) {
      // console.log(index2, index);

      // 选择时间切换时，将piaoNumber置为0
      this.dayPiao[index].piaoNumber = 0;

      // 点击时，将isActive切换成相反
      this.dayPiao[index].timeAndNumVos[index2].isActive =
        !this.dayPiao[index].timeAndNumVos[index2].isActive;

      // 除了isActive为true的，全部为false
      for (let i = 0; i < this.dayPiao[index].timeAndNumVos.length; i++) {
        if (i == index2) {
          continue;
        }
        this.dayPiao[index].timeAndNumVos[i].isActive = false;
      }
      this.calculateTotal();
      this.calculateTotalPrice();

      this.$forceUpdate();
    },
    // 获取评价详细信息
    getpingjiaInfo() {
      pingjiaInfoApi(this.jingquId)
        .then((res) => {
          if (res.code === 200) {
            this.pingjiaInfo = res.data;
          } else {
            this.pingjiaInfo = {
              goodPercent: 100,
              pingjiaCount: 0,
              orderCount: 0,
            };
          }
        })
        .catch((err) => {
          console.log(err);
          this.pingjiaInfo = {
            goodPercent: 100,
            pingjiaCount: 0,
            orderCount: 0,
          };
        });
    },

    // 点击tabs
    clickTabs(e) {
      uni.pageScrollTo({
        scrollTop: 0, // 滚动到顶部
        duration: 300, // 滚动动画时长，单位为毫秒，默认值为300
      });

      if (this.isActiveTabs == e.index) {
        return;
      } else {
        this.isActiveTabs = e.index;
        if (e.index == 1) {
          this.getPiaoByJingquIdFun();
        } else if (e.index == 2) {
          setTimeout(()=>{
            // 评价
            this.getpingjiaInfo();
            this.getpingjiaNum(); // 获取评价个数
            this.getpingjiaList();
          },500);
        }
      }
    },

    // 通过景区id获取景区的详细信息
    getJingQuInfo(jingquId) {
      getDetailsByJingquIdAPI(jingquId)
        .then((res) => {
          if (res.code === 200) {
            let jingquTips = res.data.jingquTips;
            this.infoObj = res.data;
            this.infoObj.jingquTips = jingquTips.split(",");

            this.infoObj.lat = res.data.lat;
            this.infoObj.lon = res.data.lon;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },

    // 导航
    toNavigation() {
      let self = this;
      // 询问用户授权获取位置
      uni.authorize({
        scope: "scope.userLocation",
        success: () => {
          uni.getLocation({
            type: "gcj02",
            isHighAccuracy: true,
            success(res) {
              // console.log(res);
              uni.showLoading({
                title: "加载中...",
              });
              this.latitude = res.latitude;
              this.longitude = res.longitude;

              let latitude = parseFloat(self.infoObj.lat);
              let longitude = parseFloat(self.infoObj.lon);
              let name = self.infoObj.jingquName;
              let address = self.infoObj.jingquAddress;

              setTimeout(() => {
                uni.openLocation({
                  latitude: latitude,
                  longitude: longitude,
                  scale: 15,
                  name,
                  address,
                  complete(res) {
                    uni.hideLoading();
                    // console.log(res);
                  },
                });
              }, 10);
            },
            fail(err) {
              console.log(err);
            },
          });
        },
        fail: (err) => {
          console.log("授权失败");
          uni.getLocation({
            type: "gcj02",
            isHighAccuracy: true,
            success(res) {
              // console.log(res);
              this.latitude = res.latitude;
              this.longitude = res.longitude;

              let latitude = Number(this.infoObj.lat);
              let longitude = Number(this.infoObj.lon);
              let name = this.infoObj.jingquName;
              let address = this.infoObj.jingquAddress;

              setTimeout(() => {
                uni.openLocation({
                  latitude: latitude,
                  longitude: longitude,
                  scale: 15,
                  name,
                  address,
                  complete(res) {
                    console.log(res);
                  },
                });
              }, 500);
            },
            fail(err) {
              console.log(err);
            },
          });
        },
      });
    },

    clickNotice() {},
    // 下拉刷新函数
    getNewInfo() {
      this.pingjiaListArr = [];
      if (this.isChooseInfo == 0) {
        this.params0 = {
          jingquId: this.jingquId,
          pageNum: 1,
          pageSize: 10,
          type: 0,
        };
      } else if (this.isChooseInfo == 1) {
        this.params1 = {
          jingquId: this.jingquId,
          pageNum: 1,
          pageSize: 10,
          type: 1,
        };
      } else {
        this.params2 = {
          jingquId: this.jingquId,
          pageNum: 1,
          pageSize: 10,
          type: 2,
        };
      }

      this.getpingjiaList();
    },
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.getNewInfo();
  },

  // 触底事件
  onReachBottom() {
    if (this.isActiveTabs != 2) return;
    console.log(this.pingjiaListArr.length, this.total);
    this.getpingjiaList();
    if (this.pingjiaListArr.length && this.pingjiaListArr.length > this.total) {
      uni.showToast({
        title: "没有更多了",
        icon: "none",
      });
      return;
    } else {
    }
  },
};
</script>
<style>
page {
  background-color: #fff;
}
</style>
<style lang="scss" scoped>
// 样式重置
::v-deep .uniui-paperplane-filled {
  color: #268cff !important;
}

::v-deep .u-tabs__wrapper__nav {
  width: 750rp;
  height: 96rpx;
  background: #fff;
}

::v-deep .u-tabs__wrapper__nav__item {
  flex: 1;
}

::v-deep .u-tabs__wrapper__nav__line {
  transform: translate(52.5px);
}

// --------------------------------

.jq_info {
  width: 750rpx;
  height: 100vh;
  position: relative;
  background: #F3F3F3;

  .info {
    width: 100%;
    overflow-y: scroll;

    .top {
      image {
        width: 750rpx;
        height: 400rpx;
      }
    }

    .bottom {
      width: 750rpx;
      height: 100%;
      background: #fff;
      overflow-x: hidden;

      .tabs {
        width: 100%;
        height: 100%;

        .bottom_info {
          width: 100%;
          height: 100%;
          overflow-x: hidden;

          .tabs_1 {
            width: 750rpx;
            overflow-x: hidden;
            image {
              width: 750rpx !important;
            }
          }
        }
      }
    }
  }

  .top_card {
    width: 750rpx;
    margin-top: -150rpx;
    .card{
      width: 100%;
      .card_info {
        .name {
          color: #333333;
          font-weight: 500;
          line-height: 64rpx;
          font-size: 40rpx;
        }
  
        .tips {
          font-size: 24rpx;
  
          .title {
            font-size: 28rpx;
            font-weight: 500;
            color: #666666;
            line-height: 40rpx;
          }
  
          text {
            padding: 4rpx 16rpx;
            border-radius: 8rpx;
            margin-right: 16rpx;
          }
  
          .one_tips {
            background: #01756b;
            color: #fff;
          }
  
          .other_tips {
            color: #01756b;
            background: #ffffff;
            border-radius: 8rpx;
            border: 1rpx solid #01756b;
          }
        }
  
        .open {
          display: flex;
  
          .time {
            font-size: 28rpx;
            font-weight: 500;
            color: #01756b;
            line-height: 40rpx;
          }
          .open2_address {
            flex: 9;
          }
  
          .daohang {
            flex: 1.5;
            padding: 0rpx 22rpx;
            display: flex;
            align-items: center;
  
            background: rgba(38, 140, 255, 0.13);
            border-radius: 164rpx;
            font-size: 20rpx;
            color: #268cff;
            float: right;
            display: inline-block;
          }
        }
  
        .open2 {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-bottom: 64rpx;
        }
  
        .notice_v {
          height: 64rpx;
          line-height: 64rpx;
          position: absolute;
          bottom: 0;
          left: 0;
          right: 0;
        }
        ::v-deep .u-notice-bar {
          padding-top: 6rpx !important;
          padding-bottom: 6rpx !important;
        }
      }
    }

  }
}

.tabs_2 {
  height: 100%;
  background: #fff;
}

.to_bobao {
  width: 112rpx;
  height: 112rpx;
  position: fixed;
  right: 40rpx;
  bottom: 140rpx;
}

.pingjia_num {
  width: 100%;
  height: 48rpx;
  display: flex;
  margin: 32rpx;

  view {
    margin-right: 32rpx;
    min-width: 128rpx;
    height: 48rpx;
    line-height: 48rpx;
    text-align: center;
    border-radius: 64rpx;
    font-size: 24rpx;
    font-weight: 400;
    background: #f4f6f8;
    color: #999999;
  }

  .isChooseInfo {
    background: rgba(14, 149, 137, 0.1);
    color: rgba(14, 149, 137, 1);
  }
}
</style>
